import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt


image = cv.imread('/Users/apple/Desktop/data/blox.jpg')
grayImg = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
grayImg = np.float32(grayImg)
cv.imshow('1 - Original image', image)


# Harris I：
harrisI = image.copy()
dst = cv.cornerHarris(grayImg, 2, 3, 0.04)
dst = cv.dilate(dst, None)
harrisI[dst > 0.01 * dst.max()] = [0, 0, 255]
cv.imshow('2 - Harris I', harrisI)


# Harris II：修正角点，从13行膨胀操作后接起
harrisII = image.copy()
ret, dst = cv.threshold(dst, 0.01 * dst.max(), 255, 0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv.connectedComponentsWithStats(dst)  # 阈值分割后找重心
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 100, 0.001)  # 定义迭代次数
corners = cv.cornerSubPix(grayImg, np.float32(centroids), (5, 5), (-1, -1), criteria)  # 角点定位到子像素

res = np.hstack((centroids, corners))  # 绘制角点，红色为原始标记，绿色为修正后
res = np.int0(res)
harrisII[res[:, 1], res[:, 0]] = [0, 0, 255]
harrisII[res[:, 3], res[:, 2]] = [0, 255, 0]
cv.imshow('3 - Harris II', harrisII)


# SIFT
siftImg = image.copy()
sift = cv.xfeatures2d.SIFT_create()
kp, des = sift.detectAndCompute(siftImg, None)
siftImg = cv.drawKeypoints(siftImg, kp, siftImg, color=(255, 0, 255))  # 画出特征点，并显示为紫色圆圈
cv.imshow('4 - SIFT image', siftImg)


# FAST
fastImg = image.copy()
fast = cv.FastFeatureDetector_create(threshold=20, nonmaxSuppression=True, type=cv.FAST_FEATURE_DETECTOR_TYPE_9_16)
kp = fast.detect(fastImg, None)
fastImg = cv.drawKeypoints(fastImg, kp, fastImg, color=(255, 0, 0))
print("Threshold: ", fast.getThreshold())  # 输出阈值
print("nonmaxSuppression: ", fast.getNonmaxSuppression())  # 是否使用非极大值抑制
print("Total Keypoints with nonmaxSuppression: ", len(kp))  # 特征点个数
cv.imshow('5 - FAST image', fastImg)


# ORB
orbImg = image.copy()
orb = cv.ORB_create()
kp = orb.detect(orbImg, None)
kp, des = orb.compute(orbImg, kp)
img2 = cv.drawKeypoints(orbImg, kp, orbImg, color=(0, 255, 255), flags=0)
cv.imshow('6 - ORB image', orbImg)



cv.waitKey()
cv.destroyAllWindows()
